package com.zzsy.shoppingpro.user.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.zzsy.shoppingpro.R;
import com.zzsy.shoppingpro.basebean.BaseBean;
import com.zzsy.shoppingpro.home.acitivty.HomeActivity;
import com.zzsy.shoppingpro.http.BaseCallback;
import com.zzsy.shoppingpro.http.RetrofitHelper;
import com.zzsy.shoppingpro.server.MainService;
import com.zzsy.shoppingpro.user.bean.GetCodeBean;
import com.zzsy.shoppingpro.user.bean.PhoneLoginBean;
import com.zzsy.shoppingpro.utils.SPHelper;
import com.zzsy.shoppingpro.utils.StringUtils;
import com.zzsy.shoppingpro.utils.Toast;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 登录页面
 */

public class LoginActivity extends Activity implements View.OnClickListener {

    private TextView tvLoginCode;
    private Button btnLogin;
    private ImageButton imgWB;
    private ImageButton imgQQ;
    private ImageButton imgWechat;
    private EditText etPhone;
    private EditText etCode;
    private CusCountDown cusCountDown;
    private String msgId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // 初始化倒计时类
        cusCountDown = new CusCountDown(this, 60);
        initUI();
    }

    /**
     * 初始化数据
     */
    private void initUI() {
        //获取电话号
        etPhone = findViewById(R.id.et_login_phone);
        //获取验证码
        etCode = findViewById(R.id.et_login_pwd);
        //点击获取验证码
        tvLoginCode = findViewById(R.id.ib_login_visible);
        tvLoginCode.setOnClickListener(this);
        //点击进行登录
        btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);
        //微博
        imgWB = findViewById(R.id.ib_weibo);
        //qq
        imgQQ = findViewById(R.id.ib_qq);
        //微信
        imgWechat = findViewById(R.id.ib_wechat);
        imgWB.setOnClickListener(this);
        imgQQ.setOnClickListener(this);
        imgWechat.setOnClickListener(this);

    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    /**
     * 点击事件的接口
     */
    @Override
    public void onClick(View v) {
        String phoneNumStr = String.valueOf(etPhone.getText());
        String verCodeStr = String.valueOf(etCode.getText());
        switch (v.getId()) {
            //点击获取验证码
            case R.id.ib_login_visible:
                showSoftInputFromWindow(LoginActivity.this,etPhone);
                if(StringUtils.isEmpty(phoneNumStr) || phoneNumStr.length() != 11 ){
                    Toast.show(LoginActivity.this,"电话为空或者格式错误！");
                    return;
                }
                cusCountDown.start();
                sendSmsGetCode(phoneNumStr);
                break;
            //点击进行登录
            case R.id.btn_login:

                if (StringUtils.isEmpty(phoneNumStr) || phoneNumStr.length() != 11) {
                    Toast.show(LoginActivity.this, "电话号码格式不正确！");
                    return;
                }
                if (StringUtils.isEmpty(verCodeStr) || verCodeStr.length() != 6) {
                    Toast.show(LoginActivity.this, "验证码格式不正确！");
                    return;
                }

                phoneLogin(phoneNumStr, verCodeStr);

                break;
            //微博
            case R.id.ib_weibo:
                Toast.show(LoginActivity.this,"该功能暂未开通！");
                break;
            //qq
            case R.id.ib_qq:
                Toast.show(LoginActivity.this,"该功能暂未开通！");
                break;
            //微信
            case R.id.ib_wechat:
                Toast.show(LoginActivity.this,"该功能暂未开通！");
                break;

        }
    }

    /**
     * 调取后台接口 进行电话号登录
     * */
    private void phoneLogin(String phoneNumStr, String verCodeStr) {
        RetrofitHelper.create(MainService.class)
                .getPhoneLogin(phoneNumStr,msgId,verCodeStr)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseCallback<BaseBean<PhoneLoginBean>>() {
                    @Override
                    public void success(BaseBean<PhoneLoginBean> phoneLoginBeanBaseBean) {
                        //  登录的token
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "jwt", phoneLoginBeanBaseBean.getData().getJwt());
                        //地址
                        String address;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getAddress())) {
                            address = "";
                        } else {
                            address = phoneLoginBeanBaseBean.getData().getAddress();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "address", address);
                        //生日
                        String birthday;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getBirthday())) {
                            birthday = "";
                        } else {
                            birthday = phoneLoginBeanBaseBean.getData().getBirthday();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "birthday", birthday);

                        //用户头像
                        String HeadImgUrl;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getHeadImgUrl())) {
                            HeadImgUrl = "";
                        } else {
                            HeadImgUrl = phoneLoginBeanBaseBean.getData().getHeadImgUrl();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "HeadImgUrl",HeadImgUrl );
                        //用户id
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "id", phoneLoginBeanBaseBean.getData().getId());
                        //身份证号
                        String IdCard;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getIdCard())) {
                            IdCard = "";
                        } else {
                            IdCard = phoneLoginBeanBaseBean.getData().getIdCard();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "IdCard", IdCard);
                        //积分
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "Integral", phoneLoginBeanBaseBean.getData().getIntegral());
                        //卡号
                        String MemberNum;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getMemberNum())) {
                            MemberNum = "";
                        } else {
                            MemberNum = phoneLoginBeanBaseBean.getData().getMemberNum();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "MemberNum", MemberNum);
                        //用户名称
                        String Name;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getName())) {
                            Name = "";
                        } else {
                            Name = phoneLoginBeanBaseBean.getData().getName();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "Name", Name);
                        //密码
                        String PayPwd;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getPayPwd())) {
                            PayPwd = "";
                        } else {
                            PayPwd = phoneLoginBeanBaseBean.getData().getPayPwd();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "PayPwd", PayPwd);
                        //电话号
                        String Phone;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getPhone())) {
                            Phone = "";
                        } else {
                            Phone = phoneLoginBeanBaseBean.getData().getPhone();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "Phone", Phone);

                        //充值余额
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "RechargeBalance", phoneLoginBeanBaseBean.getData().getRechargeBalance());
                        //会员卡姓名
                        String RealName;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getRealName())) {
                            RealName = "";
                        } else {
                            RealName = phoneLoginBeanBaseBean.getData().getRealName();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "RealName", RealName);
                        //性别
                        String Sex;
                        if (StringUtils.isEmpty(phoneLoginBeanBaseBean.getData().getSex())) {
                            Sex = "";
                        } else {
                            Sex = phoneLoginBeanBaseBean.getData().getSex();
                        }
                        SPHelper.setSimpleKeyValue(LoginActivity.this, "Sex",Sex );
                        // 进入首页页面
                        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                        finish();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Toast.show(LoginActivity.this,"请检查网络哦！");
                    }
                });

    }

    /**
     * 调取后台接口 获取短信验证码
     * */
    private void sendSmsGetCode(String phoneNumStr) {

        RetrofitHelper.create(MainService.class)
                .postPhoneCode(phoneNumStr)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseCallback<BaseBean<GetCodeBean>>() {
                    @Override
                    public void success(BaseBean<GetCodeBean> getCodeBeanBaseBean) {
                        if(getCodeBeanBaseBean.getCode() != 200){
                           Toast.show(LoginActivity.this,getCodeBeanBaseBean.getMsg());
                           return;
                        }
                        Toast.show(LoginActivity.this,getCodeBeanBaseBean.getMsg());
                        msgId = getCodeBeanBaseBean.getData().getMsgId();
                    }


                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Toast.show(LoginActivity.this,"请检查网络哦！");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 根据倒计时 获取验证码
     */
    public class CusCountDown extends CountDownTimer {

        private static final int TIME = 1000;
        private Context contexts;

        public CusCountDown(Context context, long millisInFuture) {
            super(millisInFuture * 1000, TIME);
            this.contexts = context;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvLoginCode.setText(String.format(contexts.getString(R.string.count_down), millisUntilFinished / TIME));
            tvLoginCode.setClickable(false);
            tvLoginCode.setTextColor(getResources().getColor(R.color.secondary_text));
        }

        @Override
        public void onFinish() {
            tvLoginCode.setText("重新获取");
            tvLoginCode.setClickable(true);
            tvLoginCode.setTextColor(getResources().getColor(R.color.red));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cusCountDown.cancel();
    }
}
